// 二次封装axios
import axios from "axios";
import store from "@/store";
import { ElMessage } from "element-plus";
import config from "@/config";

let baseUrl =
  process.env.NODE_ENV === "development"
    ? config.baseUrl.dev
    : config.baseUrl.pro;
if (sessionStorage.getItem("url")) {
  baseUrl = sessionStorage.getItem("url");
}
const Request = axios.create({
  baseURL: baseUrl,
  withCredentials: true, // send cookies when cross-domain requests跨域请求时发送cookie
  timeout: 115000, // 请求的最大时间（超时）
});

// request interceptor请求拦截器
Request.interceptors.request.use(
  (config) => {
    // do something before request is sent 在发送请求之前做点什么
    const { token = "", UserInfo = {} } = store.getters;
    if (config.type === "form-data") {
      config.headers["Content-Type"] = "multipart/form-data";
    }
    if (token) {
      // let each request carry token  /让每个请求携带以下令牌
      config.headers["user-code"] = UserInfo.user_code || "";
      config.headers["username"] = UserInfo.mobile || "";
      // config.headers['Token'] = token
      config.headers["Authorization"] = token;
    }
    return config;
  },
  (error) => {
    // do something with request error 处理请求错误
    console.log(error); // for debug
    return Promise.reject(error);
  }
);
// response interceptor 响应拦截器
Request.interceptors.response.use(
  (response) => {
    const res = response.data;
    if (res.success) {
      return res.data; // 成功就返回data数据
    } else {
      // 如果是token过期，就让它去登录页
      if (res.data == "redirect") {
        store.dispatch("user/clearInfo").then(() => {
          location.reload(); // 为了重新实例化vue-router对象 避免bug
        });
      }
      // 失败就在页面显示失败原因
      ElMessage({
        message: res.msg,
        type: "error",
        duration: 5 * 1000,
      });
      return Promise.reject(res.msg || "Error");
    }
  },
  (error) => {
    console.log("err", error); // for debug
    // 如果是token过期，就让它去登录页
    if (error.response && error.response.status && error.response.status === 401) {
      store.dispatch("user/clearInfo").then(() => {
        location.reload(); // 为了重新实例化vue-router对象 避免bug
      });
    }

    ElMessage({
      message: error.message,
      type: "error",
      duration: 5 * 1000,
    });
    return Promise.reject(error);
  }
);

export default Request;
